﻿using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace StockTradTest.Data
{
    public class GetStockInfo
    {
        //上证，深证
        //http://query.sse.com.cn/security/stock/downloadStockListFile.do?csrcCode=&stockCode=&areaName=&stockType=1
        //http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1110&TABKEY=tab1&random=0.8250613136903342
        public static string GetCsvOfSH()
        {
            string url = "http://query.sse.com.cn/security/stock/downloadStockListFile.do?csrcCode=&stockCode=&areaName=&stockType=1";
            WebClient client = new WebClient();
            //上证读取必须包含表头
            client.Headers.Add("X-Requested-With", "XMLHttpRequest");
            client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/56.0.2924.87 Safari/537.36");
            client.Headers.Add("Referer", "http://www.sse.com.cn/assortment/stock/list/share/");
            //注册GB2312，否则读取乱码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            client.Encoding = Encoding.GetEncoding("GB2312");
            try
            {

                var value = client.DownloadString(url);

                return value;
            }
            catch (WebException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        public static byte[] GetXlsxOfSZ()
        {
            string url = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1110&TABKEY=tab1&random=0.8250613136903342";
            WebClient client = new WebClient();
            try
            {
                var value = client.DownloadData(url);
                return value;
            }
            catch (WebException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        //转化CSV格式
        public static List<StockInfo> ConvertSHCsvToData(string csvString)
        {
            try
            {
                string[] dataList = csvString.Split('\n');
                string[] aryline;
                List<StockInfo> list = new List<StockInfo>();
                if (dataList.Length < 2) return null;
                for (int i = 1; i < dataList.Length - 1; i++)
                {

                    aryline = dataList[i].Split(new char[] { '\t' });
                    StockInfo et = new StockInfo()
                    {
                        Code = aryline[0],
                        Name = aryline[1].Replace(" ", ""),
                        StartDate = int.Parse(aryline[4].Replace(" ", "").Replace("-", "")),

                    };

                    list.Add(et);
                }
                return list;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        //转化Xlsx格式
        public static List<StockInfo> ConvertSZXlsxToData(byte[] xlsxBytes)
        {
            try
            {
                //bytes转为内存文件流，然后转化
                MemoryStream stream = new MemoryStream();
                stream.Write(xlsxBytes, 0, xlsxBytes.Length);
                Console.WriteLine(xlsxBytes.Length);
                List<StockInfo> list = new List<StockInfo>();
                IWorkbook workbook = WorkbookFactory.Create(stream);
                ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作薄
                int length = sheet.LastRowNum;
                for(int i = 1; i < length;i++)
                {
                    IRow row = (IRow)sheet.GetRow(i);//获取第i行
                    //剔除非主板股票
                    if (row.GetCell(0).ToString() != "主板") continue;
                    StockInfo et = new StockInfo()
                    {
                        Code = row.GetCell(4).ToString(),
                        Name = row.GetCell(5).ToString(),
                        StartDate = int.Parse(row.GetCell(6).ToString().Replace("-", "")),

                    };
                    list.Add(et);
                }
                
                return list;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        //每日实时更新
        public static async IAsyncEnumerable<string> UpdateInfoAsync()
        {
            yield return "上证股票列表信息获取中\r\n";
            string value = GetCsvOfSH();
            yield return ("上证股票列表信息获取完毕\r\n");
            var infos = ConvertSHCsvToData(value);

            yield return "深证股票列表信息获取中\r\n";
            var bytes = GetXlsxOfSZ();
            yield return ("深证股票列表信息获取完毕\r\n");
            var infos2 = ConvertSZXlsxToData(bytes);
            infos = infos.Union(infos2).ToList();
            if (infos == null) yield break;
            yield return ("股票列表信息存储中\r\n");
            await Base.StockInfoDatabase.SaveAllStockInfoAsync(infos);
            yield return ("股票列表信息存储成功\r\n");
        }
    }
}
